package com.egame.manage.biz.web.controller.op;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import cn.egame.common.servlet.WebUtils;
import cn.egame.common.util.Utils;
import cn.egame.interfaces.EnumType.AppParameterParamType;
import cn.egame.interfaces.EnumType.GameStatus;
import cn.egame.interfaces.EnumType.GameTagType;
import cn.egame.interfaces.EnumType.GameType;
import cn.egame.interfaces.fl.FileInfo;
import cn.egame.interfaces.fl.FileUsedType;
import cn.egame.interfaces.fl.FileUtils;
import cn.egame.interfaces.gc.GameInfo;
import cn.egame.interfaces.gc.GameTagInfo;
import cn.egame.interfaces.pu.AppParameter;

import com.egame.manage.biz.server.ManageClient;
import com.egame.manage.biz.server.gc.GameServiceImpl;
import com.egame.manage.biz.server.gc.GameTagServiceImpl;
import com.egame.manage.biz.server.pu.ParameterServiceImpl;
import com.egame.manage.biz.server.pu.StoreSortServiceImpl;
import com.egame.manage.biz.utils.ConstantVar;
import com.egame.manage.biz.web.controller.BaseController;
import com.lenovo.manager.business.domain.UserBean;

@Controller
@RequestMapping("/store/game")
public class GameTopicController extends BaseController {

	public GameTopicController(){		
	}
	public GameTopicController(HttpServletRequest req, HttpServletResponse resp) {
		super(req, resp);
	}
	
	@RequestMapping(value = "/topic/list", method = {RequestMethod.GET,RequestMethod.POST})
	public ModelAndView listGameTopic(HttpServletRequest req, HttpServletResponse resp) throws Exception{
		if(req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY) != null){
			UserBean userBean = (UserBean) req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY);
			loginUserId = userBean.getOperatorId();
		}	
		AppParameter bean = new AppParameter();
		bean.setBeginTime(null);
		bean.setEndTime(null);
		//专题名
		String banner = WebUtils.getString(req, "banner","");
		String beginTime = WebUtils.getString(req, "beginTime","");
		String endTime = WebUtils.getString(req, "endTime","");
		bean.setName(banner);
		if(""!=beginTime){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date beginDate = sdf.parse(beginTime);
			bean.setBeginTime(beginDate);
		}
		if(""!=endTime){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date endDate = sdf.parse(endTime);
			bean.setEndTime(endDate);
		}
		bean.setParentId(ConstantVar.STORE_GAME_TOPIC);
		bean.setEnable(true);//开启状态
		ModelAndView mv = new ModelAndView("/new/op/store/gameTopicList");	
		//应用专题列表
		List<Integer> appTopicIds = StoreSortServiceImpl.getInstance().listAppParameterByBean(appId, loginUserId, bean);
		//List<Integer> appTopicIds = ManageClient.getInstance().listAppParameterIdsByParentId(appId, loginUserId, ConstantVar.STORE_GAME_TOPIC);
		//TODO
		//此处可换成按bean检索
		List<AppParameter> appTopicList = new ArrayList<AppParameter>();
		if((appTopicIds != null)&&(appTopicIds.size()>0)){
			for(Integer appIds:appTopicIds){
				appTopicList.add(ManageClient.getInstance().getAppParameterById(appId, loginUserId, appIds)) ;
			}
		}
		appTopicList = checkAdvertiseValid(appTopicList);
		mv.addObject("appTopicList", appTopicList);
		mv.addObject("banner", banner);
		mv.addObject("beginTime", beginTime);
		mv.addObject("endTime", endTime);
		return mv;
	}
	
	//新增跳转
	@RequestMapping(value = "/topic/set/show", method = {RequestMethod.GET,RequestMethod.POST})
	public ModelAndView showNewAdvertisement(HttpServletRequest req, HttpServletResponse resp)throws Exception{
		return new ModelAndView("/new/op/store/newGameTopic");
	}	
	
	//新增提交
	@RequestMapping(value = "/topic/new", method = {RequestMethod.GET,RequestMethod.POST})
	public ModelAndView newAdv(HttpServletRequest req, HttpServletResponse resp,AppParameter bean,String beginAdv,String endAdv) throws Exception{
		if(req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY) != null){
			UserBean userBean = (UserBean) req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY);
			loginUserId = userBean.getOperatorId();
		}	
		try{							
			bean.setBeginTime(bean.getBeginTime());
			bean.setEndTime(bean.getEndTime());					
		}catch(Exception e){
			bean.setBeginTime(new Date());
			bean.setEndTime(new Date());
		}	
		ModelAndView mv = new ModelAndView("/new/op/store/gameTopicSort");
		bean.setOperatorId((int)loginUserId);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date beginTime = sdf.parse(beginAdv);
		Date endTime = sdf.parse(endAdv);
		bean.setBeginTime(beginTime);
		bean.setEndTime(endTime);
		bean.setDepth(4);
		bean.setEnable(true);
		if(bean.getRemark()==null||bean.getRemark()==""){
			bean.setRemark("");
		}
		int maxSortNo = ParameterServiceImpl.getInstance().getMaxSortNo(ConstantVar.STORE_GAME_TOPIC);
		bean.setSort(1+maxSortNo);	
		bean.setUpdateTime(new Date());
		bean.setParentId(ConstantVar.STORE_GAME_TOPIC);
		Map<AppParameterParamType, String> param = new HashMap<AppParameterParamType, String>();
		param.put(AppParameterParamType.menu_page_type, "1");
		param.put(AppParameterParamType.menu_type, "1");
		bean.setParam(param);
		bean.setType(ManageClient.getInstance().getAppParameterById(appId, loginUserId, ConstantVar.STORE_GAME_TOPIC).getType());
		ManageClient.getInstance().setAppParameter(appId, loginUserId, bean);
		int topicId = ParameterServiceImpl.getInstance().getIdByNameAndParentId(bean.getName(), bean.getRemark(), bean.getParentId());
		GameTagInfo gametagInfo = new GameTagInfo();
		gametagInfo.setTagName(String.valueOf(topicId));
		gametagInfo.setTagType(GameTagType.gameParameterAppTag);
		gametagInfo.setEnable(1);
		gametagInfo.setCountClick(0);
		gametagInfo.setCountGame(10);
		gametagInfo.setRemark("appMenuTag");
		GameTagServiceImpl.getInstance().setGameTagInfo(gametagInfo);
		mv.addObject("topicId", topicId);
		mv.addObject("bean", bean);
		mv.addObject("beginAdv", beginAdv);
		mv.addObject("endAdv", endAdv);
		return mv;
	}
	
	//取消新增专题
	@RequestMapping(value = "/topic/delete/add", method = {RequestMethod.GET,RequestMethod.POST})
	public ModelAndView deleteAdd(int topic,HttpServletRequest req, HttpServletResponse resp)throws Exception{
		//可用做提示框验证条件
		StoreSortServiceImpl.getInstance().deleteSort(appId, loginUserId, topic);
		return listGameTopic(req, resp);
	}
	
	//添加应用
	@RequestMapping(value = "/topic/sort", method = {RequestMethod.GET,RequestMethod.POST})
	public ModelAndView addSortList(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		if(req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY) != null){
			UserBean userBean = (UserBean) req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY);
			loginUserId = userBean.getOperatorId();
		}	
		ModelAndView mv = new ModelAndView("/new/op/store/gameTopicSort");
		int sortSelect = WebUtils.getInt(req, "topicId", 0);
		int tagid = ManageClient.getInstance().getGameTagIdByAppParameterId(appId, loginUserId, sortSelect);
		List<Integer> recommendGids = ManageClient.getInstance().listGameIdByGameTagId(appId,loginUserId,tagid);
		List<GameInfo> recommendtmp = ManageClient.getInstance().listGameInfoByIds(appId, loginUserId, recommendGids);
		List<GameInfo> recommendList = new ArrayList<GameInfo>();
		//对推荐游戏进行排序
		if(recommendtmp != null && recommendtmp.size()>0){
			for(int gid:recommendGids){
				for(GameInfo tmpBean:recommendtmp){
					if(tmpBean != null && tmpBean.getGId() == gid){
						recommendList.add(tmpBean);
					}
				}
			}
		}		
		//过滤推荐游戏
		String recommendName = WebUtils.getString(req, "recommendname","");			
		if(!Utils.stringIsNullOrEmpty(recommendName)){	
			int rid = Utils.toInt(recommendName, 0);
			String rName = rid>0?"":recommendName.trim();
			if(rid>0){
				int i=0;
				while(i<recommendList.size()){
					if(recommendList.get(i).getGId() != rid){
						recommendList.remove(i);
					}else{
						i++;
					}
				}
			}else if(rName.length()>0){
				int i=0;
				while(i<recommendList.size()){
					if(recommendList.get(i).getGameName() != null 
							&& recommendList.get(i).getGameName().indexOf(rName)<0){
						recommendList.remove(i);
					}else{
						i++;
					}
				}
			}			
		}	
		
		String gameName = WebUtils.getString(req, "gname","");
		List<Integer> gids = new ArrayList<Integer>();
		List<GameInfo> gameList = new ArrayList<GameInfo>();		
		if(!Utils.stringIsNullOrEmpty(gameName)){
			int gid = Utils.toInt(gameName, 0);
			String name = gid>0?"":gameName.trim();			
			gids = GameServiceImpl.getInstance().listGIdByTypeAndName(appId, loginUserId, gid, name, GameStatus.business.value(), GameType.shop.value());
			gameList = ManageClient.getInstance().listGameInfoByIds(appId, loginUserId, gids);					
		}	
		//去除推荐游戏	
		gameList.removeAll(recommendList);
		int topicId = WebUtils.getInt(req, "topicId", 0);
		mv.addObject("recommendList", recommendList);
		mv.addObject("gameList", gameList);
		mv.addObject("gameName", gameName);
		mv.addObject("recommendName", recommendName);
		mv.addObject("topicId", topicId);
				
		return mv;
	}
	
	@RequestMapping(value = "/topic/sort/increase", method = {RequestMethod.GET,RequestMethod.POST})	
	public ModelAndView addRecommendGame(int select,HttpServletRequest req, HttpServletResponse resp) throws Exception{
		List<Integer> gids = listGid(req,resp);
		int tagid = ManageClient.getInstance().getGameTagIdByAppParameterId(appId, loginUserId, select);
		for(int gid:gids){
			GameTagServiceImpl.getInstance().addTagLink(appId, loginUserId, gid, tagid, 0, -1);
		}		
		return addSortList(req, resp);
	}
	
	@RequestMapping(value = "/topic/sort/decrease", method = {RequestMethod.GET,RequestMethod.POST})	
	public ModelAndView deleteRecommendGame(int select,HttpServletRequest req, HttpServletResponse resp) throws Exception{
		List<Integer> gids = listGid(req,resp);
		int tagid = ManageClient.getInstance().getGameTagIdByAppParameterId(appId, loginUserId,select);
		for(int gid:gids){
			GameTagServiceImpl.getInstance().deleteTagLink(appId, loginUserId, gid, tagid);
		}		
		return addSortList(req, resp);
	}
	
	//确认提交
	@RequestMapping(value = "/topic/sort/add", method = {RequestMethod.GET,RequestMethod.POST})
	public ModelAndView submitSortList(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		if(req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY) != null){
			UserBean userBean = (UserBean) req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY);
			loginUserId = userBean.getOperatorId();
		}	
		return listGameTopic(req, resp);
	}
	//删除
	@RequestMapping(value = "/topic/delete", method = {RequestMethod.GET,RequestMethod.POST})
	public ModelAndView deleteAdvertisement(int id,HttpServletRequest req, HttpServletResponse resp)throws Exception{
		if(req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY) != null){
			UserBean userBean = (UserBean) req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY);
			loginUserId = userBean.getOperatorId();
		}
		//可用做提示框验证条件
		StoreSortServiceImpl.getInstance().deleteSort(appId, loginUserId, id);
		return listGameTopic(req, resp);
	}
	//编辑跳转
	@RequestMapping(value = "/topic/edit/show", method = {RequestMethod.GET,RequestMethod.POST})
	public ModelAndView editHomeAdvertisement(HttpServletRequest req, HttpServletResponse resp)throws Exception{
		if(req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY) != null){
			UserBean userBean = (UserBean) req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY);
			loginUserId = userBean.getOperatorId();
		}
		
		int id = WebUtils.getInt(req,"id",0);	
		AppParameter bean = ManageClient.getInstance().getAppParameterById(appId, loginUserId, id);
		ModelAndView mv = new ModelAndView("/new/op/store/editGameTopic"); 
		//TODO
		//文件路径
		FileInfo file = ManageClient.getInstance().getFileInfo(appId, loginUserId, bean.getPicId());
		if(file == null) file = new FileInfo();
		String filepath =cn.egame.interfaces.ConstVar.DOWNLOAD_URL + FileUtils.getFilePath(FileUsedType.file, bean.getPicId(), file.getFileName());
		mv.addObject("bean", bean);
		mv.addObject("filepath", filepath);
		return mv;
	}
	//编辑提交
	@RequestMapping(value = "/topic/set/edit", method = {RequestMethod.GET,RequestMethod.POST})
	public ModelAndView setHXAdvertisement(AppParameter bean,HttpServletRequest req, HttpServletResponse resp)throws Exception{

		if(req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY) != null){
			UserBean userBean = (UserBean) req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY);
			loginUserId = userBean.getOperatorId();
		}
		try{							
			bean.setBeginTime(bean.getBeginTime());
			bean.setEndTime(bean.getEndTime());					
		}catch(Exception e){
			bean.setBeginTime(new Date());
			bean.setEndTime(new Date());
		}	
		bean.setUpdateTime(new Date());	
		ManageClient.getInstance().setAppParameter(appId, loginUserId, bean);
		return listGameTopic(req, resp);
	}
	//历史数据
	@RequestMapping(value = "/topic/history/list", method = {RequestMethod.GET,RequestMethod.POST})
	public ModelAndView listHXHistoryActivity(HttpServletRequest req, HttpServletResponse resp) throws Exception{
		if(req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY) != null){
			UserBean userBean = (UserBean) req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY);
			loginUserId = userBean.getOperatorId();
		}
		ModelAndView mv = new ModelAndView("/new/op/store/gameHisTopic");
		AppParameter bean = new AppParameter();
		bean.setEnable(false);//关闭状态
		bean.setParentId(ConstantVar.STORE_GAME_TOPIC);
		bean.setType(ManageClient.getInstance().getAppParameterById(appId, loginUserId, ConstantVar.STORE_GAME_TOPIC).getType());
		
		//TODO
		//历史数据检索
		List<Integer> historyIds = StoreSortServiceImpl.getInstance().listTopicHistoryIdsByParentId(appId, loginUserId, ConstantVar.STORE_GAME_TOPIC);
		List<AppParameter> topicHisList = ManageClient.getInstance().listAppParameterByIds(appId, loginUserId, historyIds);
		mv.addObject("topicHisList", topicHisList);
		
		return mv;
	}
	//上移
	@RequestMapping(value = "/topic/upper", method = {RequestMethod.GET,RequestMethod.POST})
	public ModelAndView upperSortNo(HttpServletRequest req, HttpServletResponse resp)throws Exception{
		if(req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY) != null){
			UserBean userBean = (UserBean) req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY);
			loginUserId = userBean.getOperatorId();
		}
		int advertiseId = WebUtils.getInt(req,"id",0);
		StoreSortServiceImpl.getInstance().upper(appId, loginUserId, advertiseId);
		//StoreAdvertiseServiceImpl.getInstance().upper(appId, loginUserId, advertiseId);		
		return listGameTopic(req,resp);
	}	
	//下移
	@RequestMapping(value = "/topic/lower", method = {RequestMethod.GET,RequestMethod.POST})
	public ModelAndView lowerSortNo(HttpServletRequest req, HttpServletResponse resp)throws Exception{
		if(req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY) != null){
			UserBean userBean = (UserBean) req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY);
			loginUserId = userBean.getOperatorId();
		}
		int advertiseId = WebUtils.getInt(req,"id",0);
		StoreSortServiceImpl.getInstance().lower(appId, loginUserId, advertiseId);
		return listGameTopic(req,resp);
	}
	
	@RequestMapping(value = "/soft/sort/upper", method = {RequestMethod.GET,RequestMethod.POST})	
	public ModelAndView upperRecommendGame(int select,HttpServletRequest req, HttpServletResponse resp) throws Exception{
		int gid = WebUtils.getInt(req, "gid", 0);
		int tagid = ManageClient.getInstance().getGameTagIdByAppParameterId(appId, loginUserId, select);
		GameTagServiceImpl.getInstance().upper(appId, loginUserId, gid, tagid);
		return addSortList(req, resp);
	}

	@RequestMapping(value = "/soft/sort/lower", method = {RequestMethod.GET,RequestMethod.POST})	
	public ModelAndView lowerRecommendGame(int select,HttpServletRequest req, HttpServletResponse resp) throws Exception{
		int gid = WebUtils.getInt(req, "gid", 0);
		int tagid = ManageClient.getInstance().getGameTagIdByAppParameterId(appId, loginUserId, select);
		GameTagServiceImpl.getInstance().lower(appId, loginUserId, gid, tagid);
		return addSortList(req, resp);
	}
	
	@RequestMapping(value = "/soft/sort/top", method = {RequestMethod.GET,RequestMethod.POST})	
	public ModelAndView topRecommendGame(int select,HttpServletRequest req, HttpServletResponse resp) throws Exception{
		int gid = WebUtils.getInt(req, "gid", 0);
		int tagid = ManageClient.getInstance().getGameTagIdByAppParameterId(appId, loginUserId, select);
		GameTagServiceImpl.getInstance().top(appId, loginUserId, gid, tagid);
		return addSortList(req, resp);
	}

	@RequestMapping(value = "/soft/sort/down", method = {RequestMethod.GET,RequestMethod.POST})	
	public ModelAndView downRecommendGame(int select,HttpServletRequest req, HttpServletResponse resp) throws Exception{
		int gid = WebUtils.getInt(req, "gid", 0);
		int tagid = ManageClient.getInstance().getGameTagIdByAppParameterId(appId, loginUserId,select);
		GameTagServiceImpl.getInstance().down(appId, loginUserId, gid, tagid);
		return addSortList(req, resp);
	}
	
	public List<Integer> listGid(HttpServletRequest req, HttpServletResponse resp) throws Exception{
		List<Integer> gids = new ArrayList<Integer>();
		String gidString = WebUtils.getString(req, "gid", "");
		if(!Utils.stringIsNullOrEmpty(gidString)){
			String[] gidArray = gidString.split(",");
			if(gidArray != null && gidArray.length>0){
				for(String gid : gidArray){
					if(Utils.toInt(gid, 0)>0){
						gids.add(Utils.toInt(gid, 0));
					}
				}
			}
		}
		return gids;
	}
	
	public List<AppParameter> checkAdvertiseValid(List<AppParameter> validList) {
		List<AppParameter> tempList = new ArrayList<AppParameter>();
		if(validList != null &&validList.size() != 0){
			for(AppParameter ad : validList) {
				if(ad.getEndTime().getTime()>System.currentTimeMillis()){
					tempList.add(ad);
				}
			}
		}
		return tempList;
	}
}
